﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class IndexCheckMoreUpdatesThanReads : IssueTypeCheckBase
    {
        public IndexCheckMoreUpdatesThanReads()
        {
            IssueTypeId = 6003;
        }

        public override void Check()
        {
            try
            {
                // Create a Data Context 
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;

                ThresholdValue minpercentage = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 1);
                double mperc = (double)minpercentage.Value;
                var qry = from db in dc.Databases
                          from t in db.Tables
                          from i in t.Indexes
                          where i.IndexUpdates > (i.IndexSeeks + i.IndexScans + i.IndexLookups) * ((100 + mperc) / 100)
                          && i.IndexType == "NONCLUSTERED INDEX"
                          select new { DatabaseName = db.DatabaseName, IndexName = i.IndexName, TableName = t.TableName, IndexId = i.IndexID };

                foreach (var index in qry)
                {
                   

                    issue = new Issue();

                    //Get Issuetype object  And Create a new  Global issue object 
                    IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                    issue.IssueType = issueType;
                    issue.TargetId = index.IndexId;
                    issue.Description = issueType.Description.Replace("{DatabaseName}", index.DatabaseName).Replace("{IndexName}", index.IndexName).Replace("{TableName}", index.TableName).Replace("{ThresholdValue}", ((100 + mperc) / 100).ToString());

                    dc.Issues.InsertOnSubmit(issue);
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }



    }
}
